package com.sh.sales.happysales.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.sh.polymedicine.happysale.result.SimpleResult;
import com.sh.polymedicine.happysale.result.UserInfoResult;
import com.sh.polymedicine.happysale.service.envelop.HappySaleManager;
import com.sh.sales.happysales.R;
import com.sh.sales.happysales.app.AppData;
import com.sh.sales.happysales.app.utils.LoginOutUtil;
import com.sh.sales.happysales.app.utils.TimerUtil;
import com.sh.sales.happysales.base.BaseActivity;
import com.sh.sales.happysales.datautils.LocalUserInfoUtils;
import com.sh.sales.happysales.service.LoginObsever;
import com.sh.sales.happysales.view.NewToast;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Subscriber;

/**
 * Created by zhouyucheng on 2017/9/18.
 */

public class SwichPhNumActivity extends BaseActivity implements LoginObsever {
    private String TAG = "SwichPhNumActivity";
    @BindView(R.id.set_back)
    ImageView setBack;
    @BindView(R.id.profect_next)
    TextView profectNext;
    @BindView(R.id.current_phnum)
    TextView currentPhnum;
    @BindView(R.id.enter_phnum)
    EditText enterPhnum;
    @BindView(R.id.phone_code)
    EditText phoneCode;
    @BindView(R.id.btn_getcode)
    TextView btnGetcode;
    @BindView(R.id.lin_phonecode)
    LinearLayout linPhonecode;
    @BindView(R.id.enter_xiugai)
    Button enterXiugai;

    @BindView(R.id.view)
    View mview;


    private UserInfoResult mUserInfoResult;
    private boolean isChanging = false;
    private String phNum;
    private Context mContext;
    private TimerUtil timerUtil;
    private String userSign;
    private PopupWindow popupWindow;

    private Subscriber<SimpleResult> changePhAuthcodeSubscriber;
    private Subscriber<SimpleResult> changePhSubscriber;
    private int refreshSignTag = -1;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_swich_phnum);
        mContext = this;
        ButterKnife.bind(this);
        mAppManager.addActivity(this);
        mLoginObserable.registerObserver(this);
        userSign = AppData.getInstence().getmUserToken().getUserSign();
        if (timerUtil == null) {
            timerUtil = TimerUtil.getInstance(mContext);
            timerUtil.setOnTimeListener(new TimerUtil.OnTimeListener() {
                @Override
                public void onTime(int time) {
                    if (btnGetcode != null) {
                        btnGetcode.setTextColor(getApplication().getResources().getColor(R.color.colorPrimary));
                        btnGetcode.setText(time + TimerUtil.MESSAGE_EXTRAL);
                        btnGetcode.setClickable(false);
                    } else {
                        Log.i(TAG, "onTime:btnGetcode is  null ");
                    }
                }

                @Override
                public void onEnd() {
                    btnGetcode.setText(mContext.getResources().getString(
                            R.string.phone_code));
                    btnGetcode.setTextColor(getApplication().getResources().getColor(R.color.bt_login));
                    btnGetcode.setClickable(true);
                }
            });
        }
        init();
    }

    private void init() {
        mUserInfoResult = AppData.getInstence().getmUserInfoResult();
        currentPhnum.setText(mUserInfoResult.getMobile());
    }

    @OnClick({R.id.set_back, R.id.enter_xiugai, R.id.btn_getcode})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.set_back:
                if (isChanging) {
                    currentPhnum.setVisibility(View.VISIBLE);
                    linPhonecode.setVisibility(View.GONE);
                    enterXiugai.setText("修改手机号");
                    isChanging = false;
                } else {
                    mAppManager.finishActivity(this);
                }
                break;
            case R.id.enter_xiugai:
                swichView();
                break;
            case R.id.btn_getcode:
                getCode();
                break;
        }
    }

    private void getCode() {
        phNum = enterPhnum.getText().toString().trim();
        if (!isMobileNO(phNum)) {
            NewToast.makeText(SwichPhNumActivity.this, getResources().getString(R.string.canuse_phone));
            return;
        }
        refreshSignTag = 1;
        if (changePhAuthcodeSubscriber != null) {
            if (changePhAuthcodeSubscriber.isUnsubscribed()) {
                changePhAuthcodeSubscriber.unsubscribe();
            }
        }
        changePhAuthcodeSubscriber = new Subscriber<SimpleResult>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                Log.i(TAG, "onError: "+e);
                if (HappySaleManager.DATA_FAIL.equals(e.getMessage())) {
                    String message = e.getCause().getCause().getMessage();
                    NewToast.makeText(SwichPhNumActivity.this, message);
                    int ret =Integer.valueOf( e.getCause().getMessage()) ;
                    if (ret>=100&&ret<200){
                        LoginOutUtil.logOut(SwichPhNumActivity.this);
                    }
                } else if (HappySaleManager.DATA_NULL.equals(e.getMessage())) {
                    NewToast.makeText(SwichPhNumActivity.this, e.getCause().getMessage());
                } else {
                    NewToast.makeText(SwichPhNumActivity.this, "获取验证码失败，请检查网络");
                }
            }

            @Override
            public void onNext(SimpleResult mSimpleResult) {
                NewToast.makeText(SwichPhNumActivity.this, "验证码发送中...");
                timerUtil.startCountTime();
                btnGetcode.setClickable(false);
            }
        };
        mHappySaleManager.sendVerificationCode(phNum, userSign, changePhAuthcodeSubscriber).subscribe(changePhAuthcodeSubscriber);

    }

    private void swichView() {
        if (!isChanging) {
            isChanging = true;
            currentPhnum.setVisibility(View.GONE);
            linPhonecode.setVisibility(View.VISIBLE);
            enterXiugai.setText("下一步");
        } else {
            changeNumber();
        }
    }

    private void changeNumber() {
        String code = phoneCode.getText().toString().trim();
        refreshSignTag = 2;
        if (changePhSubscriber != null) {
            if (changePhSubscriber.isUnsubscribed()) {
                changePhSubscriber.unsubscribe();
            }
        }
        changePhSubscriber = new Subscriber<SimpleResult>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                Log.i(TAG, "onError: "+e);
                if (HappySaleManager.DATA_FAIL.equals(e.getMessage())) {
                    String message = e.getCause().getCause().getMessage();
                    NewToast.makeText(SwichPhNumActivity.this, message);
                    int ret =Integer.valueOf( e.getCause().getMessage()) ;
                    if (ret>=100&&ret<200){
                        LoginOutUtil.logOut(SwichPhNumActivity.this);
                    }
                } else if (HappySaleManager.DATA_NULL.equals(e.getMessage())) {
                    NewToast.makeText(SwichPhNumActivity.this, e.getCause().getMessage());
                } else {
                    NewToast.makeText(SwichPhNumActivity.this, "修改手机号失败，请检查网络");
                }
            }

            @Override
            public void onNext(SimpleResult o) {
                mUserInfoResult.setMobile(phNum);
                LocalUserInfoUtils.updataUserInfoResult(mUserInfoResult, mUserInfoResult.getInfoId());
                currentPhnum.setVisibility(View.VISIBLE);
                linPhonecode.setVisibility(View.GONE);
                currentPhnum.setText(phNum);
                enterXiugai.setText("修改手机号");
                isChanging = false;
                showBindNum();
            }
        };
        mHappySaleManager.bindMobile(phNum, code, userSign, changePhSubscriber).subscribe(changePhSubscriber);
    }

    private void showBindNum() {
        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View contentview = inflater.inflate(R.layout.pop_finish_swichphnum, null);
        contentview.setFocusable(true); // 这个很重要
        contentview.setFocusableInTouchMode(true);
        popupWindow = new PopupWindow(contentview, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(false);
        ImageView img = (ImageView) contentview.findViewById(R.id.set_back);
        TextView changedphone = (TextView) contentview.findViewById(R.id.changed_phone);
        changedphone.setText(phNum);
        Intent mIntent = new Intent();
        mIntent.putExtra("phNum", phNum);
        // 设置结果，并进行传送
        this.setResult(6, mIntent);
        img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindow.dismiss();
            }

        });
        contentview.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    popupWindow.dismiss();
                    return true;
                }
                return false;
            }
        });
        popupWindow.showAtLocation(mview, Gravity.CENTER, 0, 0);
    }

    /**
     * 验证手机格式
     */
    public static boolean isMobileNO(String mobiles) {
    /*
    移动：134、135、136、137、138、139、150、151、157(TD)、158、159、187、188
    联通：130、131、132、152、155、156、185、186
    电信：133、153、180、189、（1349卫通）
    总结起来就是第一位必定为1，第二位必定为3或5或8，其他位置的可以为0-9
    */
        String telRegex = "[1][7358]\\d{9}";//"[1]"代表第1位为数字1，"[358]"代表第二位可以为3、5、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。
        if (TextUtils.isEmpty(mobiles)) return false;
        else return mobiles.matches(telRegex);
    }

    @Override
    protected void onDestroy() {
        if (timerUtil != null) {
            timerUtil.StopTimer();
        }
        mLoginObserable.unregisterObserver(this);
        super.onDestroy();
    }


    @Override
    public void refreshUserSign(int Position) {
        userSign = AppData.getInstence().getmUserToken().getUserSign();
        switch (refreshSignTag) {
            case 1:
                getCode();
                break;
            case 2:
                changeNumber();
                break;
        }
    }
}
